package com.elinkway.infinitemovies.ui.activity.play;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.Utils;
import com.le123.ysdq.R;
import com.novaplayer.LetvMediaPlayerControl;

public class LiveVieoPlayerGestureHandle {

    private final String TAG = "LiveVieoPlayerGestureHandle";
    
    /**
     * 最大系统音量
     */
    private final static int VOLUME_MAX = 1500 ;
    
    private final String BRIGHTNESS = "brightness";
    private final String VOLUME = "volume";
    /**
     * 手势滑动时的起始X坐标
     */
    private float mStartXPoint;
    /**
     * 手势滑动时的起始Y坐标
     */
    private float mStartYPoint;
    
    private Activity mActivity;
    /**
     * 全屏播放页面布局
     */
    private RelativeLayout mFullScreenLayout;
    /**
     * 播放器实例，处理seekTo操作
     */
    private LetvMediaPlayerControl mPlayerController;
    /**
     * 屏幕宽度
     */
    private int mWindowWidth ;
    /**
     * 屏幕高度
     */
    private int mWindowHeight;
    /**
     * 左右滑屏
     */
    private boolean mSlideLeftAndRight;
    /**
     * 上下滑屏
     */
    private boolean mSlideUpAndDown;
    /**
     * 当前的屏幕亮度
     */
    private float mCurrentBrightness = -1f;
    /**
     * 当前的音量值
     */
    private int mCurrentVolume = -1;
    
    /**
     * 音频管理器，用于调节手机音量
     */
    private AudioManager mAudioManager;
    /**
     * 显示手势拖动时的文字
     */
    private TextView mGestureDragTextView;
    /**
     * 显示手势拖动时的图片
     */
    private ImageView mGestureImageView;
    
    /**
     * 手势拖动时用到的弹窗
     */
    public PopupWindow mGesturePopupWindow;
    
    /**
     * 手势拖动时显示什么图片，快进、快退、音量或者亮度图片
     */
    private String mGestureImageViewFlag;
    
    private PlayLiveController mLiveController;
    
    private Handler mHandler;
    
    public LiveVieoPlayerGestureHandle(Activity activity, RelativeLayout layout,
            PlayLiveController liveController, Handler handler) {
        mActivity = activity;
        mFullScreenLayout = layout;
        mWindowWidth = Utils.getWidthPixels(mActivity);
        mWindowHeight = Utils.getHeightPixels(mActivity);
        mLiveController = liveController;
        mHandler = handler;
        initGestureView();
    }
    
    /**
     * 初始化手势拖动时用到的图片和文字背景
     */
    private void initGestureView(){
        if(null == mActivity){
            return ;
        }
        LayoutInflater layoutInflater = mActivity.getLayoutInflater();
        if(null == layoutInflater){
            return ;
        }
        
        View gestureView = layoutInflater.inflate(R.layout.player_gesture_drag, null);
        if(null != gestureView){
            mGestureDragTextView = (TextView)gestureView.findViewById(R.id.gesture_textview);
            mGestureImageView = (ImageView)gestureView.findViewById(R.id.gesture_imageview);
            mGesturePopupWindow = new PopupWindow(gestureView,WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.WRAP_CONTENT);
        }
    }
    
    /**
     * 处理手势滑动的相关操作
     * ACTION_DOWN 和 ACTION_UP事件只会执行一次，
     * @param event:滑动事件
     */
    public void handleGestureSlide(MotionEvent event, LetvMediaPlayerControl player){
        if(null == event|| null == player){
             return ;
        }
        
        this.mPlayerController = player;
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
             mStartXPoint = event.getX(); 
             mStartYPoint = event.getY();
             initGestureData();
        }
        else if(event.getAction() == MotionEvent.ACTION_MOVE){
            float endXPoint = event.getX(); //手势滑动时的结束X坐标
            float endYPoint = event.getY(); //手势滑动时的结束Y坐标
           if(Math.abs(mStartXPoint - endXPoint) < Math.abs(mStartYPoint - endYPoint) 
                    && mSlideUpAndDown
                    && Math.abs(mStartYPoint - endYPoint) >= 20){
                gestureUpAndDown(mStartYPoint, endYPoint);
            }
        }
        
        else if (event.getAction() == MotionEvent.ACTION_UP){
            LogUtils.i(TAG,"***** in event.getAction() == MotionEvent.ACTION_UP *****");
            //销毁手势弹窗
            if(null != mGesturePopupWindow && mGesturePopupWindow.isShowing()){
                LogUtils.i(TAG,"***** in MotionEvent.ACTION_UP before sendMessage*****");
                mHandler.removeMessages(Utils.VIDEO_DISMISS_GESTURE_POPUPWINDOW);
                mHandler.sendEmptyMessageDelayed(Utils.VIDEO_DISMISS_GESTURE_POPUPWINDOW,
                        Utils.VIDEO_DISMISS_GESTURE_POPUPWINDOW_TIME);
            }
        }
    }
    
    /**
     * 初始化手势滑动的初始值
     */
    private void initGestureData(){
        if(null == mActivity || null == mPlayerController){
            return ;
        }
        if(null == mAudioManager){
            mAudioManager = (AudioManager)mActivity.getSystemService(Context.AUDIO_SERVICE);
        }
        mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        mCurrentBrightness = mActivity.getWindow().getAttributes().screenBrightness;
        mSlideUpAndDown = true;//ACTION_DOWN时，将两个标志位都置为true，根据第一次滑动时哪个方向的偏移量大，分别进行左右滑屏或者上下滑屏
        mSlideLeftAndRight = true;
    }
    
    /**
     * 手势调节音量和亮度
     */
    private void gestureUpAndDown(float startY,float endY){
       mSlideLeftAndRight = false;
       float percent = (startY - endY) / (2 * mWindowHeight / 3);// 2/3的屏幕拖动，要完成音量或者屏幕亮度从0%-100%的变化
       if(mStartXPoint >= (mWindowWidth / 2)){//滑屏发生在右半屏，处理音量变化
           gestureVolumeHandle(percent);
       }else{
           gestureBrightnessHandle(percent);
       }
    }
    
    /**
     *  处理屏幕亮度操作
     */
    private void gestureBrightnessHandle(float percent){
        if(mCurrentBrightness < 0){
            mCurrentBrightness = mActivity.getWindow().getAttributes().screenBrightness;
            if(mCurrentBrightness <= 0.00f)
                mCurrentBrightness = 0.50f;
            if(mCurrentBrightness < 0.01f)
                mCurrentBrightness = 0.009f;
        }
        
        mGestureImageViewFlag = BRIGHTNESS;
        WindowManager.LayoutParams lParam = mActivity.getWindow().getAttributes();
        lParam.screenBrightness = mCurrentBrightness + percent;
        if (lParam.screenBrightness > 1.0f){
            lParam.screenBrightness = 1.0f; 
        }else if (lParam.screenBrightness < 0.01f){
            lParam.screenBrightness = 0.009f;
        }
            
        mActivity.getWindow().setAttributes(lParam);
        showGestureTimeAndVolume(mGestureImageViewFlag,(int)(lParam.screenBrightness * 100)  + "%",null);
    }
    
    /**
     *  手势音量操作
     */
    private void gestureVolumeHandle(float percent){
        if(mCurrentVolume == -1 && null != mAudioManager){
            mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            if(mCurrentVolume < 0){
                mCurrentVolume = 0;
            }
        }
        
        mGestureImageViewFlag = VOLUME;
        int volumeIndex = (int)(percent * VOLUME_MAX) + mCurrentVolume * 100; //用于匹配进度条可以从0%-100%变化
        mLiveController.setCurrentVolume(volumeIndex);
        int volumeShowOnText = 100 * volumeIndex / VOLUME_MAX;
        if(volumeShowOnText > 100)
            volumeShowOnText = 100;
        else if(volumeShowOnText < 0)
            volumeShowOnText = 0;

        volumeIndex = volumeIndex / 100;
        if (volumeIndex > 15)
            volumeIndex = 15;
        else if (volumeIndex < 0)
            volumeIndex = 0;
        showGestureTimeAndVolume(mGestureImageViewFlag,volumeShowOnText + "%",null);
    }
    
    /**
     * 显示手势拖动时的弹窗 
     */
    private void showGestureTimeAndVolume(String imageViewBg, String textViewShowed,
            String forwardText) {
        if (null == mGestureDragTextView || null == mGestureImageView
                || null == mGesturePopupWindow) {
            return;
        }
        if (imageViewBg == BRIGHTNESS) {
            mGestureImageView.setImageResource(R.drawable.gesture_brightness);
            mGestureDragTextView.setText(textViewShowed);
        } else if (imageViewBg == VOLUME) {
            mGestureImageView.setImageResource(R.drawable.gesture_volume);
            mGestureDragTextView.setText(textViewShowed);
        }
        if (null != mFullScreenLayout) {
            mGesturePopupWindow.showAtLocation(mFullScreenLayout, Gravity.CENTER, 0, 0);
        }
    }
    
    
    /**
     * 销毁手势弹窗
     */
    public void dismissGesturePopupWindow() {
        if (null != mGesturePopupWindow && mGesturePopupWindow.isShowing()) {
            mGesturePopupWindow.dismiss();
        }
    }
    
    
    public void destroyResource(){
        mAudioManager = null;
        mGestureDragTextView = null;
        mGestureImageView = null;
        mGesturePopupWindow = null;
    }

}
